<template>
  <div class="multi-tab-detail-data-source-config">
    <a-tabs v-model:activeKey="activeTabKey" type="editable-card" @edit="onTabEdit">
      <a-tab-pane
        v-for="tab in tabs"
        :key="tab.key"
        :closable="tabs.length > 1"
      >
        <template #tab>
          <span v-if="!tab.isEditing" @dblclick="editTabTitle(tab)">{{ tab.title }}</span>
          <a-input 
            v-else 
            ref="titleInputRef" 
            v-model:value="tab.editTitle" 
            size="small" 
            style="width: 100px;"
            @blur="saveTabTitle(tab)"
            @keydown.enter="saveTabTitle(tab)"
          />
        </template>
        <div class="tab-content">
          <!-- 选择数据源类型 -->
          <a-form layout="inline" style="margin-bottom: 16px;">
            <a-form-item label="数据源类型">
              <a-select
                v-model:value="tab.dataSourceType"
                style="width: 200px;"
                @change="(value) => onDataSourceTypeChange(tab, value)"
              >
                <a-select-option value="list">列表数据源</a-select-option>
                <a-select-option value="detail">详情数据源</a-select-option>
              </a-select>
            </a-form-item>
          </a-form>

          <!-- 根据数据源类型显示对应的配置组件 -->
          <div class="data-source-config-wrapper">
            <!-- 详情数据源配置 -->
            <DetailDataSourceConfig
              v-if="tab.dataSourceType === 'detail'"
              :model-value="tab.dataSource"
              @update:model-value="(val) => updateTabDataSource(tab.key, val)"
            />

            <!-- 列表数据源配置 -->
            <ListDataSourceConfig
              v-else-if="tab.dataSourceType === 'list'"
              :model-value="tab.dataSource"
              @update:model-value="(val) => updateTabDataSource(tab.key, val)"
            />

            <!-- 表单数据源配置 -->
            <FormDataSourceConfig
              v-else-if="tab.dataSourceType === 'form'"
              :model-value="tab.dataSource"
              @update:model-value="(val) => updateTabDataSource(tab.key, val)"
            />

            <!-- 列表详情数据源配置 -->
            <ListDetailDataSourceConfig
              v-else-if="tab.dataSourceType === 'list-detail'"
              :model-value="tab.dataSource"
              @update:model-value="(val) => updateTabDataSource(tab.key, val)"
            />
          </div>
        </div>
      </a-tab-pane>
    </a-tabs>

    <div style="margin-top: 16px;">
      <a-button type="primary" @click="addNewTab">添加页签</a-button>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, nextTick } from 'vue';
import { message } from 'ant-design-vue';
import DetailDataSourceConfig from './DetailDataSourceConfig.vue';
import ListDataSourceConfig from './ListDataSourceConfig.vue';
import FormDataSourceConfig from './FormDataSourceConfig.vue';
import ListDetailDataSourceConfig from './ListDetailDataSourceConfig.vue';

// 定义组件的属性
const props = defineProps({
  modelValue: {
    type: Array,
    default: () => []
  }
});

// 定义组件的事件
const emit = defineEmits(['update:modelValue']);

// 当前激活的页签
const activeTabKey = ref('tab1');

// 页签数据
const tabs = ref([
  {
    key: 'tab1',
    title: '页签1',
    dataSourceType: 'detail',
    dataSource: {},
    isEditing: false,
    editTitle: '页签1'
  }
]);

// 避免循环更新的标志位
let isUpdatingFromProps = false;
let isUpdatingFromLocal = false;

// 监听props变化
watch(
  () => props.modelValue,
  (newVal) => {
    if (isUpdatingFromLocal) {
      isUpdatingFromLocal = false;
      return;
    }
    
    isUpdatingFromProps = true;
    if (Array.isArray(newVal) && newVal.length > 0) {
      tabs.value = newVal.map((tab, index) => ({
        key: tab.key || `tab${index + 1}`,
        title: tab.title || `页签${index + 1}`,
        dataSourceType: tab.dataSourceType || 'detail',
        dataSource: tab.dataSource || {},
        isEditing: false,
        editTitle: tab.title || `页签${index + 1}`
      }));
      
      // 设置激活的页签为第一个页签
      if (tabs.value.length > 0) {
        activeTabKey.value = tabs.value[0].key;
      }
    }
  },
  { immediate: true, deep: true }
);

// 监听tabs变化并触发update:modelValue事件
watch(
  () => tabs.value,
  (newVal) => {
    if (isUpdatingFromProps) {
      isUpdatingFromProps = false;
      return;
    }
    
    isUpdatingFromLocal = true;
    console.log("🚀 ~ newVal:", newVal)
    emit('update:modelValue', newVal);
  },
  { deep: true }
);

// 更新特定页签的数据源
const updateTabDataSource = (tabKey, newData) => {
  const tabIndex = tabs.value.findIndex(tab => tab.key === tabKey);
  if (tabIndex !== -1) {
    // 直接更新数据源，避免重建整个数组
    tabs.value[tabIndex].dataSource = { ...newData };
  }
};

// 添加新页签
const addNewTab = () => {
  const newTabIndex = tabs.value.length + 1;
  const newTabKey = `tab${newTabIndex}`;
  
  tabs.value.push({
    key: newTabKey,
    title: `页签${newTabIndex}`,
    dataSourceType: 'detail',
    dataSource: {}
  });
  
  activeTabKey.value = newTabKey;
};

// 页签编辑（添加/删除）
const onTabEdit = (targetKey, action) => {
  if (action === 'add') {
    addNewTab();
  } else if (action === 'remove') {
    removeTab(targetKey);
  }
};

// 删除页签
const removeTab = (targetKey) => {
  if (tabs.value.length === 1) {
    message.warning('至少保留一个页签');
    return;
  }

  const targetIndex = tabs.value.findIndex(tab => tab.key === targetKey);
  if (targetIndex !== -1) {
    tabs.value.splice(targetIndex, 1);

    // 更新激活的页签
    if (activeTabKey.value === targetKey && tabs.value.length > 0) {
      activeTabKey.value = tabs.value[Math.max(0, targetIndex - 1)].key;
    }
  }
};

// 数据源类型变更
const onDataSourceTypeChange = (tab, newType) => {
  // 当数据源类型变更时，重置数据源配置
  tab.dataSource = {};
};

// 编辑页签标题
const editTabTitle = (tab) => {
  tab.isEditing = true;
  tab.editTitle = tab.title;
  nextTick(() => {
    const input = titleInputRef.value.find(input => input?.$el?.closest(`[id$="${tab.key}"]`));
    if (input && input.focus) {
      input.focus();
    }
  });
};

// 保存页签标题
const saveTabTitle = (tab) => {
  if (tab.editTitle.trim() !== '') {
    tab.title = tab.editTitle.trim();
  }
  tab.isEditing = false;
};
</script>

<style scoped>
.multi-tab-detail-data-source-config {
  padding: 16px;
}

.tab-content {
  padding: 16px 0;
}

.data-source-config-wrapper {
  margin-top: 16px;
}

:deep(.ant-tabs-tab-remove) {
  margin-left: 8px;
}
</style>